//202102104015柴亚楠
package cn.edu.sdjzu.xg.kcsj.service;

import cn.edu.sdjzu.xg.kcsj.dao.UserDao;
import cn.edu.sdjzu.xg.kcsj.domain.User;
import cn.edu.sdjzu.xg.kcsj.domain.authority.Actor;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
public final class UserService {
    private static final UserService userService = new UserService();
    private final UserDao userDao = UserDao.getInstance();

    public UserService() {
    }
    public static UserService getInstance() {
        return UserService.userService;
    }
    public Collection<User> findAll() throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<User> users = userDao.findAll(connection);
        JdbcHelper.close(null, connection);
        return users;
    }
    public User find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        User user = userDao.find( id,connection);
        JdbcHelper.close(null, connection);
        return user;
    }
    public boolean update(User user) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean updated = false;
        try {
            updated = userDao.update(user,connection);
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }
        return updated;
    }
    public Integer add(User user) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        Integer added = 0;
        try {
            added = userDao.add(user,connection);
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }
        return added;
    }
    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean deleted = false;
        try {
            deleted = userDao.delete(id,connection);
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }
        return deleted;
    }

    public Actor login(User userToLogin) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        Actor actor = null;
        try {
            actor = userDao.login(userToLogin,connection);

        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }
        return actor;
    }
}
